package com.rjkj.medicalwaste.network.retrofit

import android.util.Log
import com.rjkj.medicalwaste.BuildConfig
import okhttp3.Call
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

//const val baseUrl = "http://121.41.194.99:12126/"
const val baseUrl = "https://www.rjzhyl.com:12126/"
val Api: ApiInterface by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
    val okHttpClient = getOkHttpClient()
    Retrofit.Builder()
        .baseUrl(baseUrl)
        .addConverterFactory(GsonConverterFactory.create())
        .callFactory(object : CallFactoryProxy(okHttpClient) {
            override fun getNewUrl(changeUrl: String, request: Request): HttpUrl {
//                Log.e("callFactory", "getNewUrl: $changeUrl", )
                return if(changeUrl.isNotEmpty()){
                    val oldUrl = request.url.toString()
                    val newUrl = oldUrl.replace(baseUrl, changeUrl)
                    newUrl.toHttpUrl()
                }else{
                    request.url
                }
            }
        })
        .build()
        .create(ApiInterface::class.java)
}


private fun getOkHttpClient(): OkHttpClient {
    val builder: OkHttpClient.Builder = OkHttpClient.Builder()
        .readTimeout(30, TimeUnit.SECONDS) //设置读取超时时间
        .writeTimeout(30, TimeUnit.SECONDS) //设置写的超时时间
        .connectTimeout(30, TimeUnit.SECONDS)
    if (BuildConfig.DEBUG) {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        builder.addInterceptor(httpLoggingInterceptor.apply {
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        })

    }
    return builder.build()
}

abstract class CallFactoryProxy(private val delegate: Call.Factory) : Call.Factory {


    override fun newCall(request: Request): Call {
        val changeUrl: String? = request.header(CHANGE_URL)
        if (changeUrl != null) {
            val newHttpUrl = getNewUrl(changeUrl, request)
            val newRequest: Request = request.newBuilder().url(newHttpUrl).build()
            return delegate.newCall(newRequest)
        }
        return delegate.newCall(request)
    }

    protected abstract fun getNewUrl(changeUrl: String, request: Request): HttpUrl

    companion object {
        private const val CHANGE_URL = "CHANGE_URL"
    }

}